package com.xzzz.irda.guardcat.server.app;

import com.xzzz.common.base.pojo.R;
import com.xzzz.common.base.util.SystemUtil;
import com.xzzz.irda.guardcat.core.pojo.Heartbeat;
import com.xzzz.irda.guardcat.server.app.pojo.MachineInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 【Server】心跳服务
 */
@Slf4j
@RestController
@RequestMapping("/guardcat")
public class GuardcatHeartbeatController {

    @Autowired
    private AppManager appManager;

    /**
     * 接收客户端心跳
     *
     * @param heartbeat 心跳
     * @param request   请求
     * @apiNote 服务端接收客户端的心跳接口
     */
    @PostMapping("/heartbeat")
    public R<?> heartbeat(@RequestBody Heartbeat heartbeat, HttpServletRequest request) {
        String remoteIp = SystemUtil.getRemoteIp(request);
        MachineInfo machine = new MachineInfo();
        BeanUtils.copyProperties(heartbeat, machine);
        machine.setRemoteIp(remoteIp);
        machine.setLastHeartbeatTime(System.currentTimeMillis());
        appManager.add(machine);
        return R.ok();
    }
}
